package com.weijun.keepalive_daemon.service

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.os.IBinder
import com.weijun.keepalive_daemon.R
import com.weijun.keepalive_daemon.logE

/**
 * @author: weijun
 * date: 2023/7/6
 * description:
 */
internal abstract class BaseService : Service() {

    companion object {
        private const val CHANNEL_ID = "48098DDD-C1F8-4CA0-9BE9-A1466CF692B2"
    }

    fun logE(msg:String) = "${javaClass.simpleName} --> $msg".logE()

    override fun onBind(intent: Intent?): IBinder? = null

    private fun defaultNotification(): Notification {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val manager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            NotificationChannel(CHANNEL_ID, "Daemon通知", NotificationManager.IMPORTANCE_DEFAULT).apply {
                enableLights(true)
                lightColor = Color.GREEN
                setShowBadge(true)
                description = "Daemon描述"
                lockscreenVisibility = Notification.VISIBILITY_PUBLIC
                enableVibration(false)
                setSound(null, null)
                manager.createNotificationChannel(this)
            }
            Notification.Builder(this, CHANNEL_ID)
                .setContentTitle("KeepAliveDemo")
                .setContentText("KeepAliveDemo is running")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.logo)
                .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.logo))
                .build()
        } else {
            Notification.Builder(this)
                .setContentTitle("KeepAliveDemo") //设置标题
                .setContentText("KeepAliveDemo is running") //设置内容
                .setWhen(System.currentTimeMillis()) //设置创建时间
                .build()
        }
    }

    private fun getNotification(): Notification {
        return defaultNotification()
    }

    override fun onCreate() {
        super.onCreate()
        logE("onCreate")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForeground(1, getNotification())
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        logE("onDestroy")
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        logE("onStartCommand")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForeground(1, getNotification())
        }
        return START_STICKY
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        logE("onTaskRemoved")
    }
}